<template>
  <j-modal
    :title="!isCopy && editId ? '编辑' : '新增'"
    :width="1200"
    :visible.sync="modalVisible"
    :maskClosable="false"
    switchFullscreen
  >
    <a-spin :spinning="submitLoading">
      <a-tabs v-model="activeKey">
        <a-tab-pane :forceRender="true" tab="基本信息" key="base">
          <base-tab-form
            ref="baseForm"
            :defaultData="editData"
            :isAdd="isCopy || !editId"
            @constituteStatusChange="constituteStatusChange"
          />
        </a-tab-pane>
        <a-tab-pane v-if="constituteStatus != 1" :forceRender="true" tab="子产品" key="product">
          <product-tab-form ref="productChildForm" :defaultData="editData" />
        </a-tab-pane>
        <a-tab-pane v-if="constituteStatus == 1" :forceRender="true" tab="采购信息" key="buyer">
          <buyer-tab-form ref="buyerForm" :defaultData="editData" />
        </a-tab-pane>
        <a-tab-pane v-if="constituteStatus == 1" :forceRender="true" tab="质检信息" key="quality">
          <quality-tab-form ref="qualityForm" :defaultData="editData" />
        </a-tab-pane>
        <a-tab-pane :forceRender="true" tab="报关信息" key="customs">
          <info-customs-tab-form ref="customsForm" :defaultData="editData" />
        </a-tab-pane>
      </a-tabs>
    </a-spin>
    <template #footer>
      <a-button @click="modalVisible = false"> 取消 </a-button>
      <a-button type="primary" :loading="submitLoading" @click="submit"> 保存 </a-button>
    </template>
  </j-modal>
</template>

<script>
import { getAction, postAction } from '@/api/manage'

import BaseTabForm from './BaseTabForm.vue'
import ProductTabForm from './ProductChildTabForm.vue'
import BuyerTabForm from './BuyerTabForm.vue'
import QualityTabForm from './QualityTabForm.vue'
import InfoCustomsTabForm from './InfoCustomsTabForm.vue'

export default {
  name: 'ArchiveInfoBasicModal',
  props: {
    // 要编辑的数据id，为空表示新增
    editId: {
      type: String,
      default: '',
    },
    // 是否为复制产品，是的话调用编辑id对应的产品数据，新增一个产品
    isCopy: {
      type: Boolean,
      default: false,
    },
    // 是否显示弹框
    visible: {
      type: Boolean,
      default: false,
    },
  },
  components: {
    BaseTabForm,
    ProductTabForm,
    BuyerTabForm,
    QualityTabForm,
    InfoCustomsTabForm,
  },
  provide() {
    return {
      getBasicForm: this,
    }
  },
  data() {
    return {
      modalVisible: this.visible,
      activeKey: 'base',
      submitLoading: false,
      editData: undefined, // 保存的从接口查到的完整产品档案详情
      constituteStatus: '1', // 产品组合状态，1单品，2组合
      url: {
        add: '/hzkj-product/product/archive/hzArchiveInfoBasic/add',
        edit: '/hzkj-product/product/archive/hzArchiveInfoBasic/edit',
        queryBasicData: '/hzkj-product/product/archive/hzArchiveInfoBasic/queryById',
        queryImgs: '/hzkj-product/product/archive/hzArchiveInfoBasic/queryHzArchiveInfoImgsByMainId',
        queryChildProduct: '/hzkj-product/product/archive/hzArchiveInfoBasic/queryHzArchiveInfoCproductByMainId',
        queryCustomsData: '/hzkj-product/product/archive/hzArchiveInfoBasic/queryHzArchiveInfoCustomsByMainId',
        queryOtherData: '/hzkj-product/product/archive/hzArchiveInfoBasic/queryHzArchiveInfoOtherByMainId',
        queryPackageData: '/hzkj-product/product/archive/hzArchiveInfoBasic/queryHzArchiveInfoPackageByMainId',
        queryQualityData: '/hzkj-product/product/archive/hzArchiveInfoBasic/queryHzArchiveInfoProductQualityByMainId',
        querySupplierData: '/hzkj-product/product/archive/hzArchiveInfoBasic/queryHzArchiveInfoSupplierByMainId',
      },
    }
  },
  watch: {
    modalVisible(val) {
      this.$emit('update:visible', val)
    },
  },
  methods: {
    constituteStatusChange(val) {
      this.constituteStatus = val
    },
    // 获取产品档案基本信息
    getBasicData() {
      return new Promise((resolve) => {
        getAction(this.url.queryBasicData, { id: this.editId }).then((res) => {
          if (res.success) {
            this.constituteStatus = res.result.constituteStatus // 设置产品组合状态
            resolve(res.result)
          } else {
            this.$message.warning(res.message)
          }
        })
      })
    },
    // 获取产品图片信息
    getImgs() {
      return new Promise((resolve) => {
        getAction(this.url.queryImgs, { id: this.editId }).then((res) => {
          if (res.success) {
            resolve(res.result)
          } else {
            this.$message.warning(res.message)
          }
        })
      })
    },
    // 获取子产品信息
    getChildProduct() {
      return new Promise((resolve) => {
        getAction(this.url.queryChildProduct, { id: this.editId }).then((res) => {
          if (res.success) {
            resolve(res.result)
          } else {
            this.$message.warning(res.message)
          }
        })
      })
    },
    // 获取报关清关信息
    getCustomsData() {
      return new Promise((resolve) => {
        getAction(this.url.queryCustomsData, { id: this.editId }).then((res) => {
          if (res.success) {
            resolve(res.result[0])
          } else {
            this.$message.warning(res.message)
          }
        })
      })
    },
    // 获取其他信息
    getOtherData() {
      return new Promise((resolve) => {
        getAction(this.url.queryOtherData, { id: this.editId }).then((res) => {
          if (res.success) {
            resolve(res.result[0])
          } else {
            this.$message.warning(res.message)
          }
        })
      })
    },
    // 获取包装信息
    getPackageData() {
      return new Promise((resolve) => {
        getAction(this.url.queryPackageData, { id: this.editId }).then((res) => {
          if (res.success) {
            resolve(res.result)
          } else {
            this.$message.warning(res.message)
          }
        })
      })
    },
    // 获取质检信息
    getQualityData() {
      return new Promise((resolve) => {
        getAction(this.url.queryQualityData, { id: this.editId }).then((res) => {
          if (res.success) {
            resolve(res.result)
          } else {
            this.$message.warning(res.message)
          }
        })
      })
    },
    // 获取供应商信息
    getSupplierData() {
      return new Promise((resolve) => {
        getAction(this.url.querySupplierData, { id: this.editId }).then((res) => {
          if (res.success) {
            resolve(res.result)
          } else {
            this.$message.warning(res.message)
          }
        })
      })
    },
    submit() {
      let arrForm = []
      let formName = []
      if (this.constituteStatus == 1) {
        arrForm = [
          this.$refs.baseForm.$refs.form.validate(),
          this.$refs.buyerForm.$refs.form.validate(),
          this.$refs.qualityForm.$refs.form.validate(),
          this.$refs.customsForm.$refs.form.validate(),
        ]
        formName = [
          { name: '基本信息', key: 'base' },
          { name: '采购信息', key: 'buyer' },
          { name: '质检信息', key: 'quality' },
          { name: '报关信息', key: 'customs' },
        ]
      } else {
        arrForm = [
          this.$refs.baseForm.$refs.form.validate(),
          this.$refs.productChildForm.$refs.form.validate(),
          this.$refs.customsForm.$refs.form.validate(),
        ]
        formName = [
          { name: '基本信息', key: 'base' },
          { name: '子产品', key: 'product' },
          { name: '报关信息', key: 'customs' },
        ]
      }
      Promise.allSettled(arrForm).then((values) => {
        const findIndex = values.findIndex((item) => item.status == 'rejected')
        if (findIndex != -1) {
          // 有校验不通过的tab
          this.$message.error(`请检查表${formName[findIndex].name}填写是否正确！`)
          this.activeKey = formName[findIndex].key // 重置到目标tab
          return
        }

        // 所有tab都通过校验，格式化数据，准备提交
        const baseForm = this.$refs.baseForm.formData
        const customsForm = this.$refs.customsForm.formData
        let otherData = {
          brand: baseForm.brand,
          color: baseForm.color,
          gw: baseForm.gw,
          heig: baseForm.heig,
          infringementLevel: baseForm.infringementLevel,
          len: baseForm.len,
          level: baseForm.level,
          material: baseForm.material,
          nw: baseForm.nw,
          size: baseForm.size,
          widt: baseForm.widt,
        }
        let sendData = {
          ...baseForm, // 基本信息
          hzArchiveInfoCustomsList: [customsForm], // 报关信息列表
          hzArchiveInfoImgsList: baseForm.hzArchiveInfoImgsList
            .split(',')
            .map((i, index) => ({ izMaster: index == 0 ? 1 : 2, url: i })), // 图片列表
          hzArchiveInfoPackageList: baseForm.packTableData, // 包装信息
        }
        delete sendData.lenWidtHeig // 删除冗余字段
        if (this.constituteStatus == 1) {
          // 单品
          const buyerForm = this.$refs.buyerForm.formData
          const qualityForm = this.$refs.qualityForm.formData
          //特殊条件判断 单品不免检的话至少需要一条质检信息
          if (qualityForm.qualityType != 1 && !qualityForm.tableData.length) {
            this.$message.error(`请至少添加一条质检项！`)
            this.activeKey = 'quality' // 重置到目标tab
            return
          }
          sendData = {
            ...sendData,
            hzArchiveInfoProductQualityList:
              qualityForm.qualityType == 1
                ? []
                : qualityForm.tableData.map((i, index) => ({
                    ...i,
                    sortNum: index + 1, // 排序号
                  })), // 质检信息, //如果是免检把值置空
            hzArchiveInfoSupplierList: buyerForm.tableData.map((i, index) => ({
              ...i,
              sortNum: index + 1, // 排序号
              attribute: i.type == 1 ? JSON.stringify(i.attribute) : i.attribute, // 属性信息
            })), // 采购信息
            hzArchiveInfoOtherList: [
              {
                ...otherData,
                buyer: buyerForm.buyer,
                qualityNum: qualityForm.qualityType == 1 ? '' : qualityForm.qualityNum, //如果是免检把值置空
                qualityRemark: qualityForm.qualityRemark,
                qualityTemplateId: qualityForm.qualityType == 1 ? '' : qualityForm.qualityTemplateId, //如果是免检把值置空
                qualityType: qualityForm.qualityType,
                remark: buyerForm.remark,
              },
            ], // 其他信息
          }
        } else {
          //组合
          const productChildForm = this.$refs.productChildForm.formData
          //特殊条件判断 组合产品至少需要一条子产品
          if (!productChildForm.tableData.length) {
            this.$message.error(`请至少添加一条子产品！`)
            this.activeKey = 'product' // 重置到目标tab
            return
          }
          sendData = {
            ...sendData,
            hzArchiveInfoCproductList: productChildForm.tableData, // 子产品列表
            hzArchiveInfoOtherList: [otherData], // 其他信息
          }
        }
        // 删除数组数据中的id，服务端不需要，可能会引起不必要的bug
        if (this.isCopy && sendData.createBy) {
          delete sendData.createBy
        }
        if (this.isCopy && sendData.createTime) {
          delete sendData.createTime
        }
        if (sendData.updateBy) {
          delete sendData.updateBy
        }
        if (sendData.updateTime) {
          delete sendData.updateTime
        }
        let clearArr = [
          ...(sendData.hzArchiveInfoCustomsList || []),
          ...(sendData.hzArchiveInfoImgsList || []),
          ...(sendData.hzArchiveInfoPackageList || []),
          ...(sendData.hzArchiveInfoProductQualityList || []),
          ...(sendData.hzArchiveInfoSupplierList || []),
          ...(sendData.hzArchiveInfoOtherList || []),
          ...(sendData.hzArchiveInfoCproductList || []),
        ]
        clearArr.forEach((item) => {
          if (item.id) {
            delete item.id
          }
          if (item.createBy) {
            delete item.createBy
          }
          if (item.createTime) {
            delete item.createTime
          }
          if (item.updateBy) {
            delete item.updateBy
          }
          if (item.updateTime) {
            delete item.updateTime
          }
        })
        if (this.isCopy) {
          // 如果是复制产品,删除冗余数据中的主id
          delete sendData.id
        } else if (this.editId) {
          // 如果是编辑产品,添加id
          sendData.id = this.editId
        }

        this.submitLoading = true
        postAction(!this.isCopy && this.editId ? this.url.edit : this.url.add, sendData)
          .then((res) => {
            if (res.success) {
              this.$message.success(`已经成功${this.editId ? '编辑' : '新增'}[${sendData.skuCode}]产品`)
              this.modalVisible = false // 关闭弹框
              this.$emit('submit', res.result) // 通知父组件提交成功
            } else {
              this.$message.error(res.message)
            }
          })
          .finally(() => {
            this.submitLoading = false
          })
      })
    },
  },
  created() {
    if (this.editId) {
      // 编辑，需要回显
      this.submitLoading = true
      Promise.all([
        this.getBasicData(),
        this.getImgs(),
        this.getChildProduct(),
        this.getCustomsData(),
        this.getOtherData(),
        this.getPackageData(),
        this.getQualityData(),
        this.getSupplierData(),
      ]).then(([base, imgs, products, custom, other, packages, qualitys, buyers]) => {
        this.editData = { base, imgs, products, custom, other, packages, qualitys, buyers }
        this.submitLoading = false
      })
    }
  },
}
</script>

<style scoped lang="less">
/deep/ .ant-form-item-label {
  width: 120px;
}
/deep/ .ant-tabs-content {
  margin-top: 20px;
}
</style>
